<template>
	<el-dialog width="500px" :show-close="false" v-model="visible" :title="!dataForm.id ? '新增' : '修改'" :close-on-click-modal="false">
		<div class="cc-flex flex-h-center">
			<div style="width: 500px">
				<el-form label-position="top" ref="dataFormRef" :model="dataForm" :rules="dataRules" label-width="80px" @keyup.enter="submitHandle()">
					<el-form-item prop="name" label="名称">
						<el-input v-model="dataForm.name"></el-input>
					</el-form-item>
					<el-form-item prop="menuIds" label="功能绑定">
						<div class="role-tree-content flex-h-100" v-if="visible">
							<el-tree
								ref="functionTreeRef"
								:filter-node-method="filterNode"
								:props="treeProps"
								:data="treeData"
								node-key="id"
								show-checkbox
								@check="onAreaSelect"
								highlight-current
								default-expand-all
								:check-strictly="true"
								:expand-on-click-node="false"
							>
								<template #default="{ data }">
									<div class="cc-flex node-item">
										<div class="title flex-h-100">
											{{ data.name }}<span class="type">{{ ` (${EFunctionTypeList.find(f => f.value == data.type)?.name})` }}</span>
										</div>
										<div class="tip cc-flex flex-0">
											<div class="offline tip-item flex-0">{{ data.code }}</div>
										</div>
									</div>
								</template>
							</el-tree>
						</div>
					</el-form-item>
				</el-form>
			</div>
		</div>
		<template #footer>
			<el-button @click="visible = false">取消</el-button>
			<el-button type="primary" @click="submitHandle()">确定</el-button>
		</template>
	</el-dialog>
</template>

<script setup lang="ts">
import { reactive, ref, onMounted, watch } from 'vue'
import { ElMessage } from 'element-plus/es'
import { MFunction, EFunctionTypeList, MRole, PermissionService } from '@/modules/permission'
import type { FormInstance, FormRules, ElTree } from 'element-plus'

const emit = defineEmits<{
	(e: 'refreshDataList', value?: string | undefined): void
}>()

const visible = ref(false)
const filterText = ref('')
const functionTreeRef = ref<InstanceType<typeof ElTree>>()
const treeData = ref<MFunction[]>([])

const dataFormRef = ref<FormInstance>()
const dataForm: MRole = reactive({
	id: undefined,
	name: '',
	menuIds: []
})
const treeProps = {
	label: 'name',
	children: 'children'
}
const dataRules = reactive<FormRules>({
	name: [{ required: true, message: '名称不能为空', trigger: ['blur', 'change'] }],
	// code: [{ required: true, message: '代码不能为空', trigger: ['blur', 'change'] }],
	menuIds: [
		{ required: true, message: '请至少选择一个选择功能', trigger: ['blur', 'change'] },
		{
			validator(rule, value, callback) {
				if (!value || value.length == 0) {
					return callback(new Error('请至少选择一个选择功能'))
				}
				return callback()
			}
		}
	]
})
onMounted(() => {
	getFunctionTree()
})

watch(filterText, val => {
	functionTreeRef.value!.filter(val)
})

const filterNode = (value: string, data: any, child: any) => {
	if (!value) return true
	return data.name.includes(value)
}
function onAreaSelect(node: MFunction, selfCheck: boolean, hasChilden: boolean) {
	dataForm.menuIds = functionTreeRef.value!.getCheckedNodes(false, false).map(f => f.id)
}
function getFunctionTree() {
	PermissionService.getFunctionTree().then((res: any) => {
		treeData.value = res
	})
}
async function init(role?: MRole) {
	visible.value = true
	// 重置表单数据
	await dataFormRef.value?.resetFields()
	if (role) {
		if (role.menuList) role.menuIds = role.menuList.map(f => f.id) as number[]
		functionTreeRef.value!.setCheckedKeys(role.menuIds)
		Object.assign(dataForm, role)
	}
}

// 表单提交
function submitHandle() {
	dataFormRef.value?.validate((valid: boolean) => {
		if (!valid) {
			return false
		}
		PermissionService.editRoleItem(dataForm).then(() => {
			visible.value = false
			emit('refreshDataList')
			ElMessage.success({
				message: '操作成功'
			})
		})
	})
}

defineExpose({
	init
})
</script>
<style scope lang="scss">
.role-tree-content {
	height: 400px;
	overflow-y: auto;
}
</style>
